package com.example.tests;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import ru.esteru.selenium.factory.WebDriverFactory;

public class GroupTests{
    private WebDriver driver;
    private String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://localhost/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testLogoutLogout() throws Exception {
        goToMainPage();
        loginAs("admin", "admin");
        logout();
    }

    @Test
    public void testChangePassword() throws Exception {
        goToMainPage();
        loginAs("admin", "admin");
        gotoUserProfile();
        editForm("123456");
        gotoUserProfile();
        setDefaultValues();
        logout();
    }


    @Test
    public void testCreateNewUser(){
        goToMainPage();
        loginAs("admin", "admin");
        gotoUserManagementConsol();
        sendFormNewUser("obygraykin", "obygraykin@bifit.com", "123456");
        logout();
    }

    @Test
    public void testCreateMovie(){
        goToMainPage();
        loginAs("admin", "admin");
        gotoAddMovie();
        sendFormNewMovie("1", "New Film", "New film in My collection", "2012", "135", "10", "All Languages");
        savingInformation();
        gotoPageHome();
        logout();
    }

    @Test
    public void testRemoveMovie(){
        goToMainPage();
        loginAs("admin", "admin");
        assertEquals("New Film", driver.findElement(By.cssSelector("div.title")).getText());
        gotoMovie("New Film (2012)");
        removeMovie();
        logout();
    }

    private void sendFormNewUser(String name, String email, String password) {
        driver.findElement(By.id("username")).clear();
        driver.findElement(By.id("username")).sendKeys(name);
        driver.findElement(By.name("email")).clear();
        driver.findElement(By.name("email")).sendKeys(email);
        driver.findElement(By.id("password")).clear();
        driver.findElement(By.name("password")).sendKeys(password);
        driver.findElement(By.id("password2")).clear();
        driver.findElement(By.name("password2")).sendKeys(password);
        // Сохраняем данные
        driver.findElement(By.name("submit")).click();
    }

    private void gotoUserProfile() {
        driver.findElement(By.linkText("My profile")).click();
    }

    private void gotoUserManagementConsol() {
        driver.findElement(By.linkText("User management")).click();
        // Переходим на страницу User management
        assertEquals("User management", driver.findElement(By.cssSelector("h2")).getText());
    }

    private void changeEmailTo(String email) {
        driver.findElement(By.id("email")).clear();
        driver.findElement(By.id("email")).sendKeys(email);
        driver.findElement(By.name("submit")).click();
    }

    private void logout() {
        driver.findElement(By.linkText("Log out")).click();
        driver.switchTo().alert().accept();
    }

    private void loginAs(String login, String password) {
        driver.findElement(By.id("username")).clear();
        driver.findElement(By.id("username")).sendKeys(login);
        driver.findElement(By.name("password")).clear();
        driver.findElement(By.name("password")).sendKeys(password);
        driver.findElement(By.name("submit")).click();
    }

    private void editForm(String password) {
        driver.findElement(By.id("password")).clear();
        driver.findElement(By.id("password")).sendKeys(password);
        // Заполняем поле повтор пароля некорректно
        driver.findElement(By.id("password2")).clear();
        driver.findElement(By.id("password2")).sendKeys(password + 1);
        driver.findElement(By.name("submit")).click();
        // Проверяем появление ошибки
        assertEquals("Both values should be the same", driver.findElement(By.cssSelector("label.error")).getText());

        // Заполняем корректными данными
        driver.findElement(By.id("password2")).clear();
        driver.findElement(By.id("password2")).sendKeys(password);
        driver.findElement(By.name("submit")).click();
        // ?Проверяем переход на сраницу User management
        assertEquals("User management", driver.findElement(By.cssSelector("h2")).getText());
    }

    private void setDefaultValues() {
        driver.findElement(By.id("password")).clear();
        driver.findElement(By.id("password")).sendKeys("admin");
        driver.findElement(By.id("password2")).clear();
        driver.findElement(By.id("password2")).sendKeys("admin");
        driver.findElement(By.name("submit")).click();
    }

    private void gotoPageHome() {
        driver.findElement(By.linkText("Home")).click();
        // Проверям переход на страницу Home
        assertEquals("New Film", driver.findElement(By.cssSelector("div.title")).getText());
    }

    private void savingInformation() {
        driver.findElement(By.cssSelector("img[alt=\"Save\"]")).click();
        // Проверяем добавление нового фильма
        try {
            assertEquals("New Film (2012)", driver.findElement(By.cssSelector("h2")).getText());
        } catch (Error e) {
            verificationErrors.append(e.toString());
        }
    }

    private void sendFormNewMovie(String imdbid, String name, String info, String date, String time, String rating, String text) {
        driver.findElement(By.name("imdbid")).clear();
        driver.findElement(By.name("imdbid")).sendKeys(imdbid);
        driver.findElement(By.name("name")).clear();
        driver.findElement(By.name("name")).sendKeys(name);
        driver.findElement(By.name("aka")).clear();
        driver.findElement(By.name("aka")).sendKeys(info);
        driver.findElement(By.name("year")).clear();
        driver.findElement(By.name("year")).sendKeys(date);
        driver.findElement(By.name("duration")).clear();
        driver.findElement(By.name("duration")).sendKeys(time);
        driver.findElement(By.name("rating")).clear();
        driver.findElement(By.name("rating")).sendKeys(rating);
        driver.findElement(By.id("text_languages_0")).clear();
        driver.findElement(By.id("text_languages_0")).sendKeys(text);
        driver.findElement(By.name("subtitles")).clear();
        driver.findElement(By.name("subtitles")).sendKeys(text);
        driver.findElement(By.name("notes")).click();
    }

    private void gotoAddMovie() {
        driver.findElement(By.cssSelector("img[alt=\"Add movie\"]")).click();
        // Проверяем переход на сраницу Add movie
        assertEquals("Add from IMDb", driver.findElement(By.cssSelector("h2")).getText());
    }

    private void gotoMovie(String nameMovie){
        driver.findElement(By.cssSelector("div.nocover")).click();
        // Проверяем переход на сраницу фильма
        try {
            assertEquals(nameMovie, driver.findElement(By.cssSelector("h2")).getText());
        } catch (Error e) {
            verificationErrors.append(e.toString());
        }
    }

    private void removeMovie() {
        driver.findElement(By.cssSelector("img[alt=\"Remove\"]")).click();
        driver.switchTo().alert().accept();
    }

    private void goToMainPage() {
        driver.get(baseUrl + "/php4dvd/");
    }

    @After
    public void tearDown() throws Exception {
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }
}
